package org.opsli.modulars.business.iot.protocol;

import io.netty.channel.Channel;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class SyncChannelUtil {

    //1是问mac地址,2是读,报警字,电池电压,版本号,3是校时,4是读历史数据,5是服务器配置,6是浓度采集周期和上传周期 7是升级开始,8是正在传输文件,9代表最后一帧,10是升级结束
    private static final Map<String, Channel> map = new ConcurrentHashMap();

    public SyncChannelUtil() {
    }

    public static void addChannel(String key, Channel channel) {
        map.put(key, channel);
    }

    public static void removeChannel(String key) {
        map.remove(key);
    }

    public static void removeChannel(Channel channel) {
        Set<Map.Entry<String, Channel>> set = map.entrySet();
        Iterator it = set.iterator();

        while(it.hasNext()) {
            Map.Entry<String, Channel> entry = (Map.Entry)it.next();
            if (((Channel)entry.getValue()).equals(channel)) {
                String key = (String)entry.getKey();
                map.remove(key);
            }
        }

    }

    public static String getkey(Channel channel) {
        String key = null;
        Set<Map.Entry<String, Channel>> set = map.entrySet();
        Iterator it = set.iterator();

        while(it.hasNext()) {
            Map.Entry<String, Channel> entry = (Map.Entry)it.next();
            if (((Channel)entry.getValue()).equals(channel)) {
                key = (String)entry.getKey();
            }
        }

        return key;
    }

    public static Channel getChannel(String key) {
        return map.size() > 0 && map.containsKey(key) ? (Channel)map.get(key) : null;
    }

    public static Boolean checkChannel(Channel channel) {
        Set<Map.Entry<String, Channel>> set = map.entrySet();
        Iterator it = set.iterator();

        Map.Entry entry;
        do {
            if (!it.hasNext()) {
                return false;
            }

            entry = (Map.Entry)it.next();
        } while(!((Channel)entry.getValue()).equals(channel));

        return true;
    }

    public static int channelSize() {
        return map.size();
    }

    public static Boolean sendMsg(String msg, String key) {
        System.out.println("key=" + key);
        if (map.size() >= 1 && map.containsKey(key)) {
            Channel channel = (Channel)map.get(key);
            if (channel.isActive()) {
                channel.writeAndFlush(msg);
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }


}
